from flask import Flask, request, send_from_directory, abort
import os
import requests

import applications.app_func

app = Flask(__name__)
base_dir = os.path.abspath(os.path.dirname(__file__))
static_dir = os.path.join(base_dir, 'static')

# 安全验证：确保static目录存在且是base_dir的子目录
if not os.path.isdir(static_dir) or not os.path.realpath(static_dir).startswith(base_dir):
    raise RuntimeError("Invalid static directory configuration")

@app.route('/<path:filename>' , methods=['GET' , 'POST'])
@app.route('/', defaults={'filename': 'index.html'}, methods=['GET' , 'POST'])
def serve_static(filename='index.html'):
    # print(filename)

    if filename.startswith('userserver/'):
        # 转发请求到用户服务器
        # 截取 userserver/ 后面的路径，并将其转发到用户服务器
        # 这里的127.0.0.1:5500是用户服务器的地址
        url = 'http://127.0.0.1:5500/' + filename[10:]
        # 判断用户请求的方法
        if request.method == 'GET':
            response = requests.get(url)
        elif request.method == 'POST':
            response = requests.post(url, data=request.data)
        else:
            abort(405)
        # 返回用户服务器的响应
        return response.content, response.status_code, response.headers.items()

    if filename.startswith('social_attack'):
        return applications.app_func.social_attack(request)
    
    if filename.startswith('socket'):
        return applications.app_func.long_socket(request)
    
    if filename.startswith('push'):
        return applications.app_func.push(request)

    # 安全拼接路径并验证是否在static目录内
    target_path = os.path.join(static_dir, filename)
    target_path = os.path.abspath(target_path)
    
    # 验证路径是否仍在static目录中
    if not target_path.startswith(static_dir):
        abort(404)
    
    # 如果是目录则返回403禁止访问
    if os.path.isdir(target_path):
        abort(403)
    
    # 返回文件内容
    #print(filename+"     "+applications.app_func.tokens_map)
    if filename in applications.app_func.tokens_map:
        type = applications.app_func.tokens_map[filename]['type']
        return send_from_directory("./socialEngine/"+type, 'index.html')
    return send_from_directory(static_dir, filename)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)